package com.dsx.plugin.exception;

import com.dsx.common.bean.Response;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;

/**
 * 全局异常处理，只处理返回json格式
 * Created by tianwenqing on 2017/5/11.
 */
@ControllerAdvice
public class ExceptionAdvice {


    public static final Logger logger = Logger.getLogger(ExceptionAdvice.class);


    /**
     * 405 不支持的请求方式
     * @param e
     * @param request
     * @return
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Response handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e , HttpServletRequest request){
        logger.error("不支持当前请求方法"+e);
        return new Response().failure(String.format("不支持%s请求方式",request.getMethod()));
    }

    /**
     * 400 参数验证失败
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    public Response handleValidationException(ValidationException e ){
        System.out.print("111111111111111111");
        //logger.error("参数验证失败",e);
        return new Response().failure("参数验证失败");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败", e);
        return new Response().failure("参数解析失败");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Response handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("不支持当前媒体类型", e);
        return new Response().failure("不支持当前媒体类型");
    }

}
